'use strict';
const strformat = require('string-format');
const urllib = require('url');
const path = require('path');
const fs = require('fs');
const Ctoaes = require('./src/ctoaes');
const CtoM3u8 = require('./src/ctom3u8');
const handle_get_m3u8 = require('./src/handle_get_m3u8');
const handle_get_pwd = require('./src/handle_get_pwd');
const handle_write_md = require('./src//handle_write_md');
const fetch = require('node-fetch');
const { env } = require('process');
// 导入koa模块
const Koa = require('koa');
// 导入koa-router模块
const Router = require('koa-router');
const cors = require('koa-cors')
const convert = require('koa-convert');
const bodyParser = require('koa-bodyparser');
const shelljs = require('shelljs');


// 创建koa-router的实例router
const router = new Router();
// 创建koa的实例app
const app = new Koa();
var options = {
    origin: 'https://saas.51cto.com',
    headers: ["Content-Type", "Content-Length", "Authorization", "Accept", "X-Requested-With"]
};



router.post('/add', async ctx => {
    // let url = ctx.URL;
    // //参数
    // let sp = url.searchParams;
    // let token = sp.get('token');
    // let title = sp.get('title');
    // let m3u8 = sp.get('m3u8');
    // let pwd = sp.get('pwd');

    let data = ctx.request.body;
    console.log(data);

    let ctom3u8 = new CtoM3u8(data.token);
    let m3u8content;
    try {
        m3u8content = await ctom3u8.down_m3u8(data.m3u8);
    }
    catch (e) {
        ctx.body = { code: 1, err: e };
        return;
    }

    try {
        m3u8content = await ctom3u8.replace_m3u8_uri_with_key(m3u8content, data.pwd);
    }
    catch (e) {
        ctx.body = { code: 2, err: e };
        return;
    }

    //写文件
    fs.writeFileSync(strformat('./ctos/{courseid}-{lessonid}.m3u8', data), m3u8content);
    fs.writeFileSync(strformat('./ctos/{courseid}-{lessonid}.json', data), JSON.stringify(data));



    ctx.body = { code: 0, title: data.title, player: strformat("https://evlon.github.io/saas51cto/webroot/play.html#{courseid}-{lessonid}", data) }

    try {
        (async function () {
            shelljs.exec('bash ./shell/gitpush.sh');
        })();
    } catch (e) {
        console.error('git push error', e);
    }

})

router.get('/m3u8/*', async ctx => {
    let url = ctx.URL;
    let matchs = /(\d+)-(\d+)/.exec(url);
    if (matchs && matchs.length == 3) {
        let fileName = "./ctos/" + matchs[0];
        let content = fs.readFileSync(fileName)
        ctx.body = content;
    }
    else {
        ctx.status == 404;
    }

})


router.get('/test', async ctx => {
    ctx.body = 'hello world';
})

app.use(bodyParser());
app.use(cors(options));
app.use(router.routes());

// 监听端口
let args = process.argv.splice(2)
let port = args[0] || 3000;
app.listen(port, () => {
    console.log("服务器已启动，http://localhost:" + port);
})

// async function process_contents(contentId,token){



//     let resp_content =  await fetch("https://saas-api.51cto.com/course/paths/contents", {
//     "headers": {
//         "accept": "application/json, text/plain, */*",
//         "authorization": token,
//         "content-type": "application/json;charset=UTF-8",
//         "sec-ch-ua": "\"Chromium\";v=\"92\", \" Not A;Brand\";v=\"99\", \"Microsoft Edge\";v=\"92\"",
//         "sec-ch-ua-mobile": "?0",
//         "sec-fetch-dest": "empty",
//         "sec-fetch-mode": "cors",
//         "sec-fetch-site": "same-site"
//     },
//     "referrer": "https://saas.51cto.com/",
//     "referrerPolicy": "strict-origin-when-cross-origin",
//     "body":  JSON.stringify({"contentIds":[{"contentId":contentId,"type":"PATH_PLATFORM"}]}),
//     "method": "POST",
//     "mode": "cors",
//     "credentials": "include"
//     });



//     let json_content = await resp_content.json();

//     console.log(json_content);


//     function(content){
//         if('COURSE_PLATFORM' == content.dataType){

//         }
//     }
//     let content_children = json_content.data[0].children;



//     'COURSE_PLATFORM'
// }



